import java.util.PriorityQueue;

public class Solution1090 {
    public int largestValsFromLabels(int[] values, int[] labels, int numWanted, int useLimit) {
        PriorityQueue<int[]> priorityQueue=new PriorityQueue<>((a,b)->b[0]-a[0]);
        for (int i=0;i<values.length;i++){
            priorityQueue.offer(new int[]{values[i],labels[i]});
        }
        int ans=0;
        int[] use=new int[20005];
        for (int i=0;i<numWanted;i++){
            if (priorityQueue.isEmpty()){
                return ans;
            }
            int[] p=priorityQueue.poll();
            while (use[p[1]]>=useLimit){
                if (priorityQueue.isEmpty()){
                    return ans;
                }
                p=priorityQueue.poll();
            }
            use[p[1]]++;
            ans+=p[0];
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1090().largestValsFromLabels(new int[]{5,4,3,2,1},new int[]{1,1,2,2,3},3,1));
    }
}
